'''
对数据进行数据可视化处理
author：wyj
'''
import json
import datetime
from pyecharts.charts import Map
from pyecharts import options as opts
from pyecharts.charts import Pie


# 读原始数据文件
today = datetime.date.today().strftime('%Y%m%d')   # 20200404
# 20200404_chinaData.json
datafile = 'data/' + today + '_chinaData.json'
with open(datafile, 'r', encoding='utf-8') as file:
    json_array = json.loads(file.read())


def chinaVisualization():
    '''
    全国疫情数据可视化（地图）
    :return:
    '''
    # 分析全国实时确诊数据：'confirmedCount'字段
    china_data = []
    for province in json_array:
        # 这边地图不能带有最后一个字省或者市之类的，不然画不了图
        china_data.append((province['provinceShortName'], province['confirmedCount']))  # (省的名字，确诊人数)
    china_data = sorted(china_data, key=lambda x: x[1], reverse=True)  # key 排序的关键字 reverse=True,表示降序，反之升序
    print(china_data)

    # 全国疫情地图
    # 自定义的每一段的范围，以及每一段的特别的样式。
    pieces = [
        {'min': 10000, 'color': '#540d0d'},
        {'max': 9999, 'min': 1000, 'color': '#9c1414'},
        {'max': 999, 'min': 500, 'color': '#d92727'},
        {'max': 499, 'min': 100, 'color': '#ed3232'},
        {'max': 99, 'min': 10, 'color': '#f27777'},
        {'max': 9, 'min': 1, 'color': '#f7adad'},
        {'max': 0, 'color': '#f7e4e4'},
    ]
    # data(省的名字，确诊人数)
    labels = [data[0] for data in china_data]
    counts = [data[1] for data in china_data]
    m = Map()
    '''
    # 系列名称，用于 tooltip 的显示，legend 的图例筛选。
    series_name: str,

    # 数据项 (坐标点名称，坐标点值)
    data_pair: Sequence,

    # 地图类型，具体参考 pyecharts.datasets.map_filenames.json 文件
    maptype: str = "china",
    '''
    m.add("累计确诊", [list(z) for z in zip(labels, counts)], 'china')
    # 系列配置项,可配置图元样式、文字样式、标签样式、点线样式等
    # 文字的字体大小,  # 是否显示标签is_show: bool = True,。
    m.set_series_opts(label_opts=opts.LabelOpts(font_size=12),
                      is_show=False)

    # 全局配置项,可配置标题、动画、坐标轴、图例等
    m.set_global_opts(title_opts=opts.TitleOpts(title='全国实时确诊数据',
                                                subtitle='数据来源：丁香园'),
                      legend_opts=opts.LegendOpts(is_show=False),
                      visualmap_opts=opts.VisualMapOpts(pieces=pieces,
                                                        is_piecewise=True,  # 是否为分段型
                                                        is_show=True))  # 是否显示视觉映射配置
    # render（）会生成本地 HTML 文件，默认会在当前目录生成 render.html 文件，也可以传入路径参数，如 m.render("mycharts.html")
    m.render('全国实时确诊数据.html')

    # 画饼状图
    # c = (
    #     Pie()
    #         .add("", [list(z) for z in zip(labels, counts)])
    #         .set_global_opts(title_opts=opts.TitleOpts(title="全国累计疫情饼状图"), legend_opts=opts.LegendOpts(is_show=False))
    #         .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}"))
    #         .render("全国累计确诊数饼状图.html")
    # )


def hubeiVisualization():
    # 分析湖北省实时确诊数据
    # 读入规范化的城市名称，用于规范化丁香园数据中的城市简称
    with open('pycharts_city.txt', 'r', encoding='UTF-8') as f:
        defined_cities = [line.strip() for line in f.readlines()]
    province_name = '湖北'
    for province in json_array:
        if province['provinceName'] == province_name or province['provinceShortName'] == province_name:
            json_array_province = province['cities']  # 这个省所有城市的数据提取出来
            hubei_confirmed_data = [(format_city_name(city['cityName'], defined_cities), city['confirmedCount'])
                                    for city in json_array_province]
            hubei_currentConfirmed_data = [(format_city_name(city['cityName'], defined_cities), city['currentConfirmedCount'])
                                    for city in json_array_province]

            print(hubei_confirmed_data)
            print(hubei_currentConfirmed_data)

    confirmed_labels = [data[0] for data in hubei_confirmed_data]
    confirmed_counts = [data[1] for data in hubei_confirmed_data]
    currentConfirmed_labels = [data[0] for data in hubei_currentConfirmed_data]
    currentConfirmed_counts = [data[1] for data in hubei_currentConfirmed_data]
    pieces = [
        {'min': 10000, 'color': '#540d0d'},
        {'max': 9999, 'min': 1000, 'color': '#9c1414'},
        {'max': 999, 'min': 500, 'color': '#d92727'},
        {'max': 499, 'min': 100, 'color': '#ed3232'},
        {'max': 99, 'min': 10, 'color': '#f27777'},
        {'max': 9, 'min': 1, 'color': '#f7adad'},
        {'max': 0, 'color': '#f7e4e4'},
    ]
    m = Map()
    m.add("累计确诊", [list(z) for z in zip(confirmed_labels, confirmed_counts)], '湖北')
    m.set_series_opts(label_opts=opts.LabelOpts(font_size=12),
                      is_show=False)
    m.set_global_opts(title_opts=opts.TitleOpts(title='湖北省实时累计确诊数据',
                                                subtitle='数据来源：丁香园'),
                      legend_opts=opts.LegendOpts(is_show=False),
                      visualmap_opts=opts.VisualMapOpts(pieces=pieces,
                                                        is_piecewise=True,
                                                        is_show=True))
    m.render('湖北省实时累计确诊数据.html')

    m2 = Map()
    m2.add("累计确诊", [list(z) for z in zip(currentConfirmed_labels, currentConfirmed_counts)], '湖北')
    m2.set_series_opts(label_opts=opts.LabelOpts(font_size=12),
                      is_show=False)
    m2.set_global_opts(title_opts=opts.TitleOpts(title='湖北省实时确诊数据',
                                                subtitle='数据来源：丁香园'),
                      legend_opts=opts.LegendOpts(is_show=False),
                      visualmap_opts=opts.VisualMapOpts(pieces=pieces,
                                                        is_piecewise=True,
                                                        is_show=True))
    m2.render('湖北省实时确诊数据.html')


def format_city_name(name, defined_cities):
    for defined_city in defined_cities:
        # (set(defined_city) & set(name)  找出相同元素
        if len((set(defined_city) & set(name))) == len(name):
            name = defined_city  # 我们自定义的城市名称可能比较完整
            if name.endswith('市') or name.endswith('区') or name.endswith('县') or name.endswith('自治州'):
                return name
            return name + '市'
    return None


# TODO 绘画福建的疫情图
def fujianVisualization():
    pass


# TODO 绘画泉州的疫情图
def quanzhouVisualization():
    pass


# TODO 绘画全球的疫情图
def globalVisualization():
    pass

if __name__ == '__main__':
    # chinaVisualization()
    hubeiVisualization()